package com.zmn.oms.zmn.business.impl.captcha;

import com.alibaba.fastjson.JSON;
import com.alibaba.nacos.api.config.annotation.NacosValue;
import com.zmn.anole.dubbo.interfaces.AnoleRemoteService;
import com.zmn.base.engineer.common.dro.foreign.engineer.ForeignEngineerMobileInfoDRO;
import com.zmn.base.engineer.dubbo.interfaces.foreign.EngineerListRemoteService;
import com.zmn.base.shortlink.common.constant.DubboConsts;
import com.zmn.base.shortlink.common.dio.shortlink.ShortLinkDIO;
import com.zmn.base.shortlink.common.dro.shortlink.ShortLinkDRO;
import com.zmn.base.shortlink.dubbo.interfaces.shortlink.ShortLinkModifyRemoteService;
import com.zmn.common.constant.GlobalConsts;
import com.zmn.common.dto2.ResponseDTO;
import com.zmn.common.utils.date.DateUtil;
import com.zmn.common.utils.math.MoneyUtil;
import com.zmn.common.utils.number.NumberUtil;
import com.zmn.common.utils.reflect.BeanMapper;
import com.zmn.common.utils.string.StringUtil;
import com.zmn.manager.redis.RedisManager;
import com.zmn.oms.business.interfaces.messageV1.common.MessageSendBaseService;
import com.zmn.oms.business.interfaces.orderamount.OrderAmountCheckBService;
import com.zmn.oms.common.constant.*;
import com.zmn.oms.common.dio.normal.captcha.GetVerificationCodeDIO;
import com.zmn.oms.common.dio.normal.captcha.ValidateVerificationCodeDIO;
import com.zmn.oms.common.exception.OmsBaseException;
import com.zmn.oms.model.dto.acceptance.OrderWorkAcceptanceDTO;
import com.zmn.oms.model.dto.messageV1.SmsMessageDTO;
import com.zmn.oms.model.entity.acceptance.OrderWorkAcceptance;
import com.zmn.oms.model.entity.detail.OrderDetail;
import com.zmn.oms.model.entity.visit.OrderVisit;
import com.zmn.oms.model.entity.visit.OrderVisitQuery;
import com.zmn.oms.model.entity.work.OrderWork;
import com.zmn.oms.services.interfaces.detail.OrderDetailService;
import com.zmn.oms.services.interfaces.visit.OrderVisitService;
import com.zmn.oms.services.interfaces.work.OrderWorkService;
import com.zmn.oms.zmn.business.interfaces.acceptance.OrderWorkAcceptanceBService;
import com.zmn.oms.zmn.business.interfaces.captcha.OrderWorkCaptchaBService;
import com.zmn.uuc.common.dro.user.UserDetailDRO;
import com.zmn.uuc.dubbo.interfaces.user.UserListRemoteService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.hbase.thirdparty.com.google.common.collect.Streams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.net.URLEncoder;
import java.util.*;


/**
 * @author yufan
 * @since 2021/11/26
 */
@Slf4j
@Service
public class OrderWorkCaptchaBServiceImpl implements OrderWorkCaptchaBService {


    //@Reference(version = com.zmn.base.engineer.common.constants.DubboConsts.INTERFACE_VERSION, check = false)
    //private BaseInfoListRemoteService baseInfoListRemoteService;

    @Reference(version = com.zmn.base.engineer.common.constants.DubboConsts.INTERFACE_VERSION, check = false)
    private EngineerListRemoteService engineerListRemoteService;

    @Reference(version = DubboConsts.INTERFACE_VERSION, check = false)
    private ShortLinkModifyRemoteService shortLinkModifyRemoteService;
    @Reference(version = AnoleRemoteService.VERSION, check = false)
    private AnoleRemoteService anoleRemoteService;
    @Reference(version = com.zmn.uuc.common.constant.DubboConsts.INTERFACE_VERSION, check = false)
    private UserListRemoteService userListRemoteService;

    @Autowired
    private MessageSendBaseService messageSendBaseService;
    @Autowired
    private OrderWorkService orderWorkService;
    @Autowired
    private OrderVisitService orderVisitService;
    @Autowired
    private OrderWorkAcceptanceBService orderWorkAcceptanceBService;
    @Autowired
    OrderDetailService orderDetailService;
    @Autowired
    OrderAmountCheckBService orderAmountCheckBService;
    @Autowired
    private RedisManager redisManager;

    @Value("${acceptance.h5.link.url:http://test2-h5.xiujiadian.com/wxuser/brand/#/subPackages/order/acceptance/%s?orderId=%s&acceptanceId=%s&orderPayId=%s&acceptVersion=%s}")
    private String ACCEPTANCE_H5_LINK_URL;
    @Value("${quotation.three.acceptance.h5.link.url:http://test2-h5.xiujiadian.com/wxuser/brand/#/subPackages/order/acceptance/faultAccept?orderId=%s&acceptanceId=%s&acceptVersion=%s}")
    private String QUOTATION_THREE_ACCEPTANCE_H5_LINK_URL;
    // 每月不同订单相同手机号验收最大数量
    @NacosValue("${acceptance.sms.limit.monthMaxPhoneCount:2}")
    private Integer SMS_LIMIT_MONTH_MAX_PHONE_COUNT;
    // 30分钟发送最大短信数量
    @NacosValue("${acceptance.sms.limit.30mMaxCount:10}")
    private Integer SMS_LIMIT_30M_MAX_COUNT;


    /**
     * 发送验证码给用户    1，将此redis key写入工具类 2，将此逻辑移入新service 3，ruleId 从配置中心获取 4.将入参类型转为枚举 5.自测
     *
     * @param getVerificationCodeDIO
     * @return
     */
    @Override
    public void sendVerificationCodeToUser(GetVerificationCodeDIO getVerificationCodeDIO) throws OmsBaseException {
        log.info("发送验证码给用户：{}", JSON.toJSONString(getVerificationCodeDIO));

        OrderWork orderWork = orderWorkService.findOrderWorkByKey(getVerificationCodeDIO.getOrderId(), getVerificationCodeDIO.getWorkId());

        Integer isCheckPhoneNum = orderAmountCheckBService.checkShowMobileInput(orderWork);

        String orderId = getVerificationCodeDIO.getOrderId().toString();
        String userPhoneNum = Optional.ofNullable(getVerificationCodeDIO.getUserPhoneNum()).orElse("");
        Integer masterId = getVerificationCodeDIO.getMasterId();
        String captcha;
        Map<String, String> map;
        int ruleId;

        String limitKey = String.format(RedisKeyConsts.ORDER_MASTERID_LIMIT_KEY, masterId);

        if (Objects.equals(isCheckPhoneNum, GlobalConsts.YES)) {
            validateUserPhoneNum(userPhoneNum, masterId);

            String incrStr = redisManager.get(limitKey);
            // 工程师半小时内十条短信限制
            log.info("sendVerificationCodeToUser#工程师发送短信次数：{}-{}，入参：{}", limitKey, incrStr, JSON.toJSONString(getVerificationCodeDIO));
            if (StringUtils.isNotBlank(incrStr) && Integer.parseInt(incrStr) >= SMS_LIMIT_30M_MAX_COUNT) {
                log.info("sendVerificationCodeToUser#验收短信（发送频繁）次数：{}-{}，最大{}，入参：{}", limitKey, incrStr, SMS_LIMIT_30M_MAX_COUNT, JSON.toJSONString(getVerificationCodeDIO));
                throw new OmsBaseException("请勿频繁发送短信，请半小时后重试");
            }

            // 相同的订单，只算一次
            String sameOrderKey = String.format(RedisKeyConsts.ORDER_SAME_ORDER_PHONE_LIMIT_KEY, orderId, userPhoneNum);
            String sameOrderPhoneStr = redisManager.get(sameOrderKey);
            if (StringUtils.isBlank(sameOrderPhoneStr)) {
                // 相同手机号，同一个工程师最大数量
                String limitPhoneKey = String.format(RedisKeyConsts.ORDER_PHONE_LIMIT_KEY, masterId, userPhoneNum);
                String incrLimitPhoneStr = redisManager.get(limitPhoneKey);
                log.info("sendVerificationCodeToUser#相同手机号使用次数：{}-{} 入参：{}", limitPhoneKey, incrLimitPhoneStr, JSON.toJSONString(getVerificationCodeDIO));
                if (StringUtils.isNotBlank(incrLimitPhoneStr) && Integer.parseInt(incrLimitPhoneStr) >= SMS_LIMIT_MONTH_MAX_PHONE_COUNT) {
                    log.info("validateVerificationCode#手机号使用次数(已超出) 次数：{}-{}，最大{}，剩余过期时间：{}，短信入参：{}", limitPhoneKey, incrLimitPhoneStr, SMS_LIMIT_MONTH_MAX_PHONE_COUNT, redisManager.ttl(limitPhoneKey), JSON.toJSONString(getVerificationCodeDIO));
                    throw new OmsBaseException("手机号本月已使用两次，请更换手机号");
                }

                // 新规则，不校验工程师id
                String acceptPhoneKey = String.format(RedisKeyConsts.ORDER_CONFIRM_PHONE_LIMIT_KEY, userPhoneNum);
                String incrAcceptPhoneStr = redisManager.get(acceptPhoneKey);
                log.info("sendVerificationCodeToUser#相同手机号使用次数：{}-{} 入参：{}", acceptPhoneKey, incrAcceptPhoneStr, JSON.toJSONString(getVerificationCodeDIO));
                if (StringUtils.isNotBlank(incrAcceptPhoneStr) && Integer.parseInt(incrAcceptPhoneStr) >= SMS_LIMIT_MONTH_MAX_PHONE_COUNT) {
                    log.info("validateVerificationCode#手机号使用次数(已超出) 次数：{}-{}，最大{}，剩余过期时间：{}，短信入参：{}", acceptPhoneKey, incrAcceptPhoneStr, SMS_LIMIT_MONTH_MAX_PHONE_COUNT, redisManager.ttl(limitPhoneKey), JSON.toJSONString(getVerificationCodeDIO));
                    throw new OmsBaseException("手机号本月已使用两次，请更换手机号");
                }
            }

        }

        //一分钟内相同验证码逻辑
        String oneMinKey = String.format(RedisKeyConsts.ORDER_CAPTCHA_SEND_LIMIT1_KEY, orderId);
        String value = redisManager.get(oneMinKey);
        if (value != null) {
            captcha = value;
        } else {
            captcha = StringUtil.getRandomsNumber(4);
            String fifteenMinKey = String.format(RedisKeyConsts.ORDER_CAPTCHA_SEND_LIMIT15_KEY, orderId);
            redisManager.setex(fifteenMinKey, captcha, 15 * 60);
            redisManager.setex(oneMinKey, captcha, 60);
        }
        // 服务验收、定金确认、费用确认
        OrderWorkAcceptance orderWorkAcceptance = orderWorkAcceptanceBService.getOrderWorkAcceptanceByAcceptanceIdAndOrderId(getVerificationCodeDIO.getAcceptanceId(), getVerificationCodeDIO.getOrderId());
        switch (orderWorkAcceptance.getAcceptanceType()) {
            case OrderConsts.ORDER_ACCEPTANCE_TYPE_PAYMENT:
            case OrderConsts.ORDER_ACCEPTANCE_TYPE_PROGRESS:
                ruleId = MessageConsts.ZMN_WECHAT_MSG_RULEID_ORDER_ACCEPTANCE_PAYMENT;
                map = new HashMap<String, String>() {
                    {
                        put("amount", getAmountByAcceptanceType(getVerificationCodeDIO.getOrderId(), orderWorkAcceptance.getAcceptanceType(), orderWork));
                        put("short_link", getShortLinkByAmountType(ruleId, orderWorkAcceptance, userPhoneNum));
                        put("code", captcha);
                    }
                };
                break;
            case OrderConsts.ORDER_ACCEPTANCE_TYPE_DEPOSIT:
                ruleId = MessageConsts.ZMN_WECHAT_MSG_RULEID_ORDER_ACCEPTANCE_DEPOSIT;
                map = new HashMap<String, String>() {
                    {
                        put("amount", getAmountByAcceptanceType(getVerificationCodeDIO.getOrderId(), orderWorkAcceptance.getAcceptanceType(), orderWork));
                        put("short_link", getShortLinkByAmountType(ruleId, orderWorkAcceptance, userPhoneNum));
                        put("code", captcha);
                    }
                };
                break;
            case OrderConsts.ORDER_ACCEPTANCE_TYPE_PAYMENT_CONFIRM:
            case OrderConsts.ORDER_ACCEPTANCE_TYPE_PROGRESS_CONFIRM:
                ruleId = MessageConsts.ZMN_MSG_RULEID_ORDER_PAY;
                map = new HashMap<String, String>() {
                    {
                        put("amount", getAmountByAcceptanceType(getVerificationCodeDIO.getOrderId(), orderWorkAcceptance.getAcceptanceType(), orderWork));
                        put("short_link", getShortLinkByAmountType(ruleId, orderWorkAcceptance, userPhoneNum));
                        put("code", captcha);
                    }
                };
                break;
            default:
                throw new OmsBaseException("type无对应数字");
        }

        if (StringUtil.isNotBlank(userPhoneNum)) {
            SmsMessageDTO smsMessageDTO = SmsMessageDTO.builder()
                    .orderId(getVerificationCodeDIO.getOrderId())
                    .businessId(getVerificationCodeDIO.getOrderId())
                    .ruleId(ruleId)
                    .mobile(userPhoneNum)
                    .channelId(String.valueOf(orderWork.getChannelId()))
                    .cityId(String.valueOf(orderWork.getCityId()))
                    .params(JSON.toJSONString(map))
                    .build();
            boolean isSuccess = messageSendBaseService.sendTextMessage(smsMessageDTO);
            if (!isSuccess) {
                throw new OmsBaseException("发送短信失败");
            }
        }

        Set<String> set = new HashSet<>(3);
        set.add(userPhoneNum);

        // 查询联系人电话
        OrderDetail orderDetail = orderDetailService.findOrderDetailByKey(getVerificationCodeDIO.getOrderId());
        if (StringUtil.isMobile(orderDetail.getTelephone())) {
            set.add(orderDetail.getTelephone());
        }

        // 查询下单用户手机号
        ResponseDTO<UserDetailDRO> userDetailDROResponseDTO = userListRemoteService.getUserDetailById(orderWork.getUserId(), false);
        UserDetailDRO userDetailDRO = userDetailDROResponseDTO.getData();
        if (Objects.nonNull(userDetailDRO) && StringUtil.isMobile(userDetailDRO.getMobile())) {
            set.add(userDetailDRO.getMobile());
        }

        log.info("[{}]发送短信确认码set:【{}】", orderId, JSON.toJSONString(set));
        set.forEach(item -> {
            if (Objects.equals(item, userPhoneNum)) {
                return;
            }

            SmsMessageDTO smsMessageDTO = SmsMessageDTO.builder()
                    .orderId(getVerificationCodeDIO.getOrderId())
                    .businessId(getVerificationCodeDIO.getOrderId())
                    .ruleId(ruleId)
                    .mobile(item)
                    .channelId(String.valueOf(orderWork.getChannelId()))
                    .cityId(String.valueOf(orderWork.getCityId()))
                    .params(JSON.toJSONString(map))
                    .build();
            boolean mobileIsSuccess = messageSendBaseService.sendTextMessage(smsMessageDTO);
            log.info("[{}]支付限制，发送联系人或下单人电话结果：{}-{}", orderId, item, mobileIsSuccess);
        });

        // 发送成功计数
        if (StringUtil.isNotBlank(userPhoneNum)) {
            Long incr = redisManager.incr(limitKey);
            if (incr == 1) {
                redisManager.expire(limitKey, 60 * 30);
            }
        }
    }

    /**
     * 获取
     *
     * @param acceptanceType
     * @return
     */
    private String getAmountByAcceptanceType(Long orderId, Integer acceptanceType, OrderWork orderWork) throws OmsBaseException {
        String amount = "";
        // 尾款
        if (Objects.equals(acceptanceType, OrderConsts.ORDER_ACCEPTANCE_TYPE_PAYMENT)
                || Objects.equals(acceptanceType, OrderConsts.ORDER_ACCEPTANCE_TYPE_PAYMENT_CONFIRM)) {
            amount = MoneyUtil.parseToYuanStr(orderWork.getMasterAmount());
        }
        // 定金或进度款
        else {
            List<OrderVisit> orderVisitList = orderVisitService.listByOrderIdSrcMaster(orderId);
            OrderVisit orderVisit = Streams.findLast(orderVisitList.stream()
                    .filter(e -> !Objects.equals(e.getVisitStatus(), OrderVisitStatusConsts.ORDER_VISIT_STATUS_CANCEL)
                            && !Objects.equals(e.getVisitStatus(), OrderVisitStatusConsts.ORDER_VISIT_STATUS_VISIT)))
                    .orElse(null);
            if (Objects.isNull(orderVisit)) {
                throw new OmsBaseException("本次上门已取消");
            } else {
                amount = MoneyUtil.parseToYuanStr(orderVisit.getAmount());
            }
        }
        if (StringUtil.isBlank(amount)) {
            return "0";
        }
        return amount;
    }

    /**
     * 短连接
     *
     * @param ruleId
     * @param orderWorkAcceptance
     * @return
     */
    private String getShortLinkByAmountType(Integer ruleId, OrderWorkAcceptance orderWorkAcceptance, String userPhoneNum) throws OmsBaseException {
        OrderWork orderWork = orderWorkService.findOrderWorkByKey(orderWorkAcceptance.getOrderId(), orderWorkAcceptance.getWorkId());
        String url = "";

        if (StringUtil.isNotBlank(userPhoneNum)) {
            // 加密手机号
            ResponseDTO<String> responseDTO = anoleRemoteService.encrypt(userPhoneNum);
            if (responseDTO.isSuccess() && StringUtil.isNotBlank(responseDTO.getData())) {
                userPhoneNum = responseDTO.getData();
            }

            // 对参数进行转码
            try {
                userPhoneNum = URLEncoder.encode(userPhoneNum, "utf-8");
            } catch (Exception e) {
                log.info("[{}]URL转码失败：[{}]", orderWorkAcceptance.getOrderId(), e.getMessage());
            }
        }

        // 计价器3.0，尾款验收专用链接
        if (Objects.equals(orderWork.getServItemType(), OrderConsts.SERVICE_ITEM_TYPE_QUOTATION_THREE)) {
            url = String.format(QUOTATION_THREE_ACCEPTANCE_H5_LINK_URL, orderWorkAcceptance.getOrderId(), orderWorkAcceptance.getAcceptanceId(), userPhoneNum);
        } else {
            String urlType = "";
            switch (orderWorkAcceptance.getAcceptanceType()) {
                case OrderConsts.ORDER_ACCEPTANCE_TYPE_DEPOSIT:
                    urlType += "deposit";
                    break;
                case OrderConsts.ORDER_ACCEPTANCE_TYPE_PAYMENT:
                case OrderConsts.ORDER_ACCEPTANCE_TYPE_PROGRESS:
                    urlType += "acceptance";
                    break;
                case OrderConsts.ORDER_ACCEPTANCE_TYPE_PAYMENT_CONFIRM:
                case OrderConsts.ORDER_ACCEPTANCE_TYPE_PROGRESS_CONFIRM:
                    urlType += "confirmPrice";
                    break;
            }

            String orderPayId = "";
            // 如果是多次上门，需要查询支付明细id
            if (NumberUtil.isNotNullOrZero(orderWorkAcceptance.getVisitId())) {
                OrderVisitQuery query = new OrderVisitQuery();
                query.setOrderId(orderWorkAcceptance.getOrderId());
                query.setVisitId(orderWorkAcceptance.getVisitId());
                OrderVisit orderVisit = orderVisitService.findOrderVisitByQuerySrcMaster(query);
                orderPayId = NumberUtil.isNotNullOrZero(orderVisit.getOrderPayId()) ? String.valueOf(orderVisit.getOrderPayId()) : "";
            }
            url = String.format(ACCEPTANCE_H5_LINK_URL, urlType, orderWorkAcceptance.getOrderId(), orderWorkAcceptance.getAcceptanceId(), orderPayId, userPhoneNum);
        }

        ShortLinkDIO shortLinkDIO = new ShortLinkDIO();
        shortLinkDIO.setBussinessId(ruleId);
        // 名字不能重复
        shortLinkDIO.setName(orderWorkAcceptance.getOrderId() + "ap:" + DateUtil.toString(DateUtil.getNow()));
        shortLinkDIO.setLink(url);
        shortLinkDIO.setValidEndTime(DateUtil.addDays(DateUtil.getNow(), 7));
        log.info("订单号【{}】获取支付限制getShortLink入参【{}】)", orderWorkAcceptance.getOrderId(), shortLinkDIO);
        ResponseDTO<ShortLinkDRO> resp = shortLinkModifyRemoteService.getShortLink(shortLinkDIO);
        log.info("订单号【{}】获取支付限制短链接getShortLink出参【{}】)", orderWorkAcceptance.getOrderId(), resp);
        if (!resp.isSuccess() || Objects.isNull(resp.getData()) || StringUtil.isBlank(resp.getData().getQrCodeId())) {
            throw new OmsBaseException("获取短信短连接失败");
        }

        return resp.getData().getQrCodeId();
    }

    /**
     * 验证订单验证码
     *
     * @param validateVerificationCodeDIO
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void validateVerificationCode(ValidateVerificationCodeDIO validateVerificationCodeDIO) throws OmsBaseException {
        Long orderId = validateVerificationCodeDIO.getOrderId();
        String userPhoneNum = validateVerificationCodeDIO.getUserPhoneNum();
        Integer masterId = validateVerificationCodeDIO.getMasterId();

        // 如果需要验收则更新验收状态
        if (NumberUtil.isNotNullOrZero(validateVerificationCodeDIO.getAcceptanceId())) {
            OrderWorkAcceptanceDTO dto = BeanMapper.map(validateVerificationCodeDIO, OrderWorkAcceptanceDTO.class);
            dto.setOperator(validateVerificationCodeDIO.getMasterName());
            dto.setOperatorId((long) validateVerificationCodeDIO.getMasterId());
            dto.setOperatorType(GlobalConsts.OPERATE_USER_TYPE_MASTER);
            dto.setAcceptanceResultStatus(OrderConsts.ORDER_ACCEPTANCE_STATUS_SUCCESS);
            dto.setAcceptanceResultType(OrderConsts.ORDER_ACCEPTANCE_RESULT_TYPE_CAPTCHA);
            orderWorkAcceptanceBService.modifyOrderWorkAcceptance(dto);
        }

        // 判断验证码是否正确
        String redisCaptcha = redisManager.get(String.format(RedisKeyConsts.ORDER_CAPTCHA_SEND_LIMIT15_KEY, orderId));
        if (redisCaptcha == null || !Objects.equals(redisCaptcha, validateVerificationCodeDIO.getCaptcha())) {
            log.info("validateVerificationCode#校验验错误：{} 入参：{}", redisCaptcha, JSON.toJSONString(validateVerificationCodeDIO));
            throw new OmsBaseException("确认码错误");
        }
        // 验证通过后，双删验证码。
        redisManager.del(RedisKeyConsts.ORDER_CAPTCHA_SEND_LIMIT1_KEY, RedisKeyConsts.ORDER_CAPTCHA_SEND_LIMIT15_KEY);

        // 相同的订单，只算一次
        String sameOrderKey = String.format(RedisKeyConsts.ORDER_SAME_ORDER_PHONE_LIMIT_KEY, orderId, userPhoneNum);
        Long sameOrderPhoneIncr = redisManager.incr(sameOrderKey);
        if (sameOrderPhoneIncr > 1L) {
            log.info("validateVerificationCode#相同的订单不计数 入参：{}", JSON.toJSONString(validateVerificationCodeDIO));
            return;
        }

        // 将通过的工程师+手机号作为key，查询是否超出每月2次限制。
        String limitKey = String.format(RedisKeyConsts.ORDER_CONFIRM_PHONE_LIMIT_KEY, userPhoneNum);
        Long incr = redisManager.incr(limitKey);

        log.info("validateVerificationCode#验收成功，相同手机号 次数：{}-{}, 入参：{}", limitKey, incr, JSON.toJSONString(validateVerificationCodeDIO));

        // 设置过期时间
        if (sameOrderPhoneIncr == 1L || incr == 1L) {
            String monthLastDay = DateUtil.getMonthLastDay(new Date());
            long dateEndTimestamp = DateUtil.getDateEndTimestamp(monthLastDay);
            // 计算本月最后一天秒数，与当前秒数时间差
            long seconds = (dateEndTimestamp - DateUtil.getNowTimestamp());
            redisManager.expire(sameOrderKey, (int) seconds);
            redisManager.expire(limitKey, (int) seconds);
        }
    }

    /**
     * 校验手机号业务合法性
     *
     * @param userPhoneNum
     * @param engineerId
     * @return
     */
    public void validateUserPhoneNum(String userPhoneNum, Integer engineerId) throws OmsBaseException {
        if (StringUtils.isEmpty(userPhoneNum)) {
            throw new OmsBaseException("请填写手机号");
        }
        boolean isMatches = StringUtil.isMobile(userPhoneNum);
        if (!isMatches) {
            throw new OmsBaseException("请填写正确的手机号");
        }
        // todo fubiao
        log.info("validateUserPhoneNum#getEngineerMobileInfoById 入参 [{}]",engineerId);
        ResponseDTO<ForeignEngineerMobileInfoDRO> basicMobileInfo = engineerListRemoteService.getEngineerMobileInfoById(engineerId);
        log.info("validateUserPhoneNum#getEngineerMobileInfoById 出参 [{}]",JSON.toJSONString(basicMobileInfo));
        ForeignEngineerMobileInfoDRO data = basicMobileInfo.getData();
        String mobile = data.getMobile();
        boolean isEngineerMobile = Objects.equals(mobile, userPhoneNum);
        if (isEngineerMobile) {
            throw new OmsBaseException("禁止使用自己手机号码，请填写用户手机号");
        }
        String urgentContactMobile = data.getUrgentContactMobile();
        boolean isUrgentContactMobile = Objects.equals(urgentContactMobile, userPhoneNum);
        if (isUrgentContactMobile) {
            throw new OmsBaseException("禁止使用紧急联系人的手机号，请填写用户手机号");
        }
    }


}
